<template>
  <view class="uni-container">
    <view class="uni-container">
      <uni-forms ref="form" :model="formData" validateTrigger="bind">
        <uni-forms-item name="title" label="采购单名称">
          <uni-easyinput placeholder="请输入采购单名称" v-model="formData.title"></uni-easyinput>
        </uni-forms-item>
        <uni-forms-item name="serial_number" label="采购单编号">
          <uni-easyinput placeholder="自动生成" v-model="formData.serial_number" :disabled="true"></uni-easyinput>
        </uni-forms-item>
        <uni-forms-item name="description" label="详细描述">
          <uni-easyinput type="textarea" placeholder="请输入规格、型号等详细信息" v-model="formData.description"></uni-easyinput>
        </uni-forms-item>
        <uni-forms-item name="start_price" label="起始价格">
          <uni-easyinput type="digit" placeholder="请输入起始价格" v-model="formData.start_price"></uni-easyinput>
        </uni-forms-item>
        <uni-forms-item name="end_time" label="报价截止时间">
          <uni-datetime-picker return-type="timestamp" v-model="formData.end_time"></uni-datetime-picker>
        </uni-forms-item>
        <uni-forms-item name="attachments" label="采购附件">
          <uni-file-picker v-model="formData.attachments" file-mediatype="all" :limit="5"></uni-file-picker>
        </uni-forms-item>
        
        <uni-forms-item name="invited_supplier_ids" label="受邀供应商">
          <!-- 从供应商角色中选择 -->
          <uni-data-checkbox
            :localdata="supplierList.map(supplier => ({ value: supplier._id, text: supplier.nickname || supplier.username || supplier._id }))"
            v-model="formData.invited_supplier_ids"
            :multiple="true"
          >
          </uni-data-checkbox>
        </uni-forms-item>
        <!-- 中标供应商字段已移除 -->
        <view class="uni-button-group">
          <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
          <button class="uni-button" style="width: 100px; margin-left: 15px;" @click="navigateBack">返回</button>
        </view>
      </uni-forms>
    </view>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/auctions.js';

  const db = uniCloud.database();
  const dbCollectionName = 'auctions';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  export default {
    data() {
      // 获取当前日期用于生成编号
      const now = new Date();
      const year = now.getFullYear();
      const month = (now.getMonth() + 1).toString().padStart(2, '0');
      const day = now.getDate().toString().padStart(2, '0');
      
      let formData = {
        "title": null,
        "serial_number": `CG-${year}${month}${day}-001`, // 默认编号格式
        "description": null,
        "start_price": null,
        "end_time": null,
        "attachments": [],
        "status": "bidding", // 默认状态为竞价中
        "invited_supplier_ids": [],
        // winner_supplier_id 已移除
        "create_time": Date.now(), // 自动生成创建时间
        "finish_time": null // 结束时间将在提交时根据截止时间生成
      }
      return {
        formData,
        supplierList: [], // 供应商列表
        formOptions: {
          "status_localdata": [
            {
              "value": "bidding",
              "text": "竞价中"
            },
            {
              "value": "finished",
              "text": "已结束"
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        },
        hasLoadedSuppliers: false // 是否已加载供应商列表
      }
    },
    mounted() {
      // 生成唯一的采购单编号
      this.generateSerialNumber();
      this.loadSupplierList();
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      /**
       * 加载供应商列表
       */
      async loadSupplierList() {
        if (this.hasLoadedSuppliers) {
          return;
        }
        console.log('开始加载供应商列表 (使用 clientDB)...');
        uni.showLoading({
          title: '加载中...'
        });

        try {
          const db = uniCloud.database();
          const res = await db.collection('uni-id-users')
            .field("ali_openid,apple_openid,avatar,avatar_file,comment,dcloud_appid,department_id,email,email_confirmed,gender,invite_time,inviter_uid,last_login_date,last_login_ip,mobile,mobile_confirmed,my_invite_code,nickname,role,score,status,username,wx_unionid,qq_unionid,tags,_id")
            .get();
          
          this.processSupplierList(res.result.data);

        } catch (err) {
          console.error('加载供应商列表失败:', err);
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        } finally {
          uni.hideLoading();
        }
      },
      
      /**
       * 处理供应商列表数据
       */
      processSupplierList(data) {
        console.log('收到的原始用户数据:', JSON.stringify(data, null, 2));

        // 过滤出供应商用户
        const suppliers = data.filter(user => {
          const isSup = this.isSupplier(user);
          console.log(`正在检查用户: ${user.username || user._id}, 是否为供应商: ${isSup}, 角色:`, user.role);
          return isSup;
        });

        console.log('过滤后的供应商列表:', JSON.stringify(suppliers, null, 2));

        this.supplierList = suppliers;
        this.hasLoadedSuppliers = true; // 标记已加载供应商列表
        
        if (suppliers.length === 0) {
          console.warn('未找到任何供应商用户');
          uni.showToast({
            title: '未找到供应商',
            icon: 'none'
          });
        } else {
          console.log(`找到 ${suppliers.length} 个供应商`);
          uni.showToast({
            title: `找到 ${suppliers.length} 个供应商`,
            icon: 'success'
          });
        }
      },
      
      /**
       * 检查用户是否为供应商
       */
      isSupplier(user) {
        // 检查用户是否有role字段
        if (!user.role) {
          return false;
        }
        
        const roles = Array.isArray(user.role) ? user.role : [user.role];
        
        return roles.some(r => {
          if (typeof r === 'string') {
            return r === 'supplier';
          }
          if (typeof r === 'object' && r !== null && r.role_id) {
            return r.role_id === 'supplier';
          }
          return false;
        });
      },
      
      /**
       * 供应商选择变化时的回调
       */
      onSupplierChange(value) {
        console.log('选择的供应商:', value)
      },
      
      /**
       * 生成唯一的采购单编号
       */
      async generateSerialNumber() {
        const now = new Date();
        const year = now.getFullYear();
        const month = (now.getMonth() + 1).toString().padStart(2, '0');
        const day = now.getDate().toString().padStart(2, '0');
        const dateStr = `${year}${month}${day}`;
        
        // 查询当天已有的采购单数量
        try {
          console.log('正在查询已有采购单数量...');
          const res = await db.collection(dbCollectionName)
            .where({
              serial_number: new RegExp(`^CG-${dateStr}-`)
            })
            .get();
          
          const count = res.result.data.length + 1;
          const serialNumber = `CG-${dateStr}-${count.toString().padStart(3, '0')}`;
          this.formData.serial_number = serialNumber;
        } catch (err) {
          console.error('生成编号失败:', err);
          // 使用默认编号
          this.formData.serial_number = `CG-${dateStr}-001`;
        }
      },
      
      /**
       * 返回上一页
       */
      navigateBack() {
        uni.navigateBack()
      },
      
      /**
       * 验证表单并提交
       */
      submit() {
        console.log('Submitting with formData:', JSON.stringify(this.formData, null, 2));
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch((err) => {
          console.log('Validation failed:', err);
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 设置创建时间
        value.create_time = Date.now();
        // 设置结束时间为截止时间
        value.finish_time = value.end_time;
        // 确保状态为竞价中
        value.status = "bidding";
        
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).add(value).then((res) => {
          uni.showToast({
            title: '新增成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      }
    }
  }
</script>